package com.ewei.web.common.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import com.ewei.web.common.exception.MessageRuntimeException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

@Component
public class Encrypter {
	private static final Logger logger = LogManager.getLogger(Encrypter.class);
	private static final String UTF8="utf-8";
	/**
	 * BASE64加密
	 * @param encode
	 * @return
	 * @throws Exception
	 */
	public String base64Encoder(String encode){
		try {
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(encode.getBytes(UTF8));
		} catch (UnsupportedEncodingException e) {
			logger.info(e);
			throw new MessageRuntimeException();
		}
	}
	/**
	 * BASE64解密
	 * @param dest
	 * @return
	 * @throws Exception
	 */
	public String base64Decoder(String dest){
		try {
			BASE64Decoder decoder = new BASE64Decoder();
			return new String(decoder.decodeBuffer(dest),UTF8);
		} catch (UnsupportedEncodingException e) {
			logger.info(e);
			throw new MessageRuntimeException(e);
		} catch (IOException e) {
			logger.info(e);
			throw new MessageRuntimeException(e);
		}
	}
} 
